import { HashRouter, Routes, Route } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import HorizontalMergePage from './pages/horizontal-merge';
import VerticalMerge from './pages/vertical-merge';
import CsvToExcel from './pages/csv-to-excel';
import Expire from './pages/expire';
import Home from './pages/home';
import Developing from './pages/developing';
import ExportLog from './pages/export-log';
import GlobalStateProvider from './biz/state-manager/global-state-context.provider';
import AntiCorruptionLayer from './biz/anti-corruption-layer';
import { createHashRouter, RouterProvider } from 'react-router-dom';
import { VerifyUtil } from './util/Verify';
import {
  DatabaseOutlined,
  MenuFoldOutlined,
  EyeFilled,
  BugFilled,
  MenuUnfoldOutlined,
  HomeOutlined,
} from '@ant-design/icons';
import { MenuProps, Empty, Menu } from 'antd';
import './App.css';
import { MenuInfo } from 'rc-menu/lib/interface';
import MLog from './util/main-log';
import UrlPath from './biz/router/url-path';

type MenuItem = Required<MenuProps>['items'][number];
const TAG = 'App';

const firstPage = UrlPath.VERTICAL_MERGE;
const firstSub = 'sub1';

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}

const router = createHashRouter([
  {
    path: UrlPath.HOME_PAGE,
    element: <Home />,
  },
  {
    path: UrlPath.EXPIRE,
    element: <Expire />,
  },
  {
    path: UrlPath.DEVELOPING,
    element: <Developing />,
  },
  {
    path: UrlPath.EXPORT_LOG,
    element: <ExportLog />,
  },
  {
    path: UrlPath.CSV2EXCEl,
    element: <CsvToExcel />,
  },
  {
    path: UrlPath.HORIZONTAL_MERGE,
    element: <HorizontalMergePage />,
  },
  {
    path: UrlPath.VERTICAL_MERGE,
    element: <VerticalMerge />,
  },
]);

export default function App() {
  const [collapsed, setCollapsed] = useState(false);
  const [selectItem, setSelectItem] = useState('');
  const [isExpired, setIsExpired] = useState(true);
  const checkExpire = () => {
    VerifyUtil.checkExpire()
      .then(() => {
        setIsExpired(false);
      })
      .catch((err) => {
        setIsExpired(true);
      });
  };
  useEffect(() => {
    // 在组件挂载时绑定监听器
    window.addEventListener('popstate', handleLocationChange);
    // 在组件卸载时清除监听器
    return () => {
      window.removeEventListener('popstate', handleLocationChange);
    };
  }, []);

  useEffect(() => {
    if (isExpired) {
      window.location.href = `#${UrlPath.EXPIRE}`;
    } else {
      window.location.href = `#${UrlPath.HOME_PAGE}`;
    }
  }, [isExpired]);
  const handleLocationChange = () => {
    setSelectItem(window.location.hash.substr(1));
    checkExpire();
  };

  const onClickItem = (info: MenuInfo) => {
    if (isExpired) {
      window.location.href = `#${UrlPath.EXPIRE}`;
      return;
    }
    switch (info.key) {
      case UrlPath.FLOD:
        setCollapsed(!collapsed);
        break;
      default:
        window.location.href = `#${info.key}`;
        break;
    }
  };
  const items: MenuItem[] = [
    getItem(
      '折叠导航',
      UrlPath.FLOD,
      collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />
    ),
    getItem('主页', UrlPath.HOME_PAGE, <HomeOutlined />),
    getItem('数据预处理', 'sub1', <DatabaseOutlined />, [
      getItem('CSV转EXCEl', UrlPath.CSV2EXCEl),
      getItem('垂直合并', UrlPath.VERTICAL_MERGE),
      getItem('水平合并', UrlPath.HORIZONTAL_MERGE),
    ]),

    getItem('数据可视化', 'sub2', <EyeFilled />, [
      getItem('开发中', UrlPath.DEVELOPING),
    ]),
    getItem('调试', 'sub3', <BugFilled />, [
      getItem('导出日志', UrlPath.EXPORT_LOG),
    ]),
  ];

  return (
    <div id="container">
      <Menu
        id="menu"
        defaultSelectedKeys={[firstPage]}
        defaultOpenKeys={[firstSub]}
        selectedKeys={[selectItem]}
        onClick={onClickItem}
        mode="inline"
        theme="light"
        inlineCollapsed={collapsed}
        items={items}
      />
      <div id="content-container">
        <GlobalStateProvider>
          <AntiCorruptionLayer>
            <RouterProvider router={router} />
          </AntiCorruptionLayer>
        </GlobalStateProvider>
      </div>
    </div>
  );
}
